<template>
  <div class="bookshelf-container">
    <div class="bookshelf-header">
      <h2 class="bookshelf-title">我的书架</h2>
      <div class="bookshelf-actions">
        <el-button 
          type="danger" 
          :disabled="selectedBooks.length === 0"
          @click="handleBatchDelete"
        >
          批量删除
        </el-button>
        <span class="book-count">共 {{ total }} 本书</span>
      </div>
    </div>
    
    <div v-if="displayBooks.length === 0" class="empty-bookshelf">
      <el-empty description="暂无收藏的书籍"></el-empty>
    </div>
    
    <div v-else class="books-grid">
      <div v-for="book in displayBooks" :key="book.title" class="book-card">
        <div class="book-cover" @click="goToDetail(book)">
          <img :src="book.coverUrl" :alt="book.title" />
          <div class="book-category">{{ book.categoryName }}</div>
          <div class="read-status" :class="{'reading': book.readStatus === 1}">
            {{ book.readStatus === 1 ? '在读' : '未读' }}
          </div>
        </div>
        <div class="book-info">
          <div class="book-header">
            <h3 class="book-title" @click="goToDetail(book)">{{ book.title }}</h3>
            <el-checkbox 
              v-model="book.selected" 
              @change="handleSelectionChange(book)"
            ></el-checkbox>
          </div>
          <div class="book-author">{{ book.authorName }}</div>
          <div class="book-progress">
            <div class="last-read">上次读到：{{ book.lastReadChapter }}</div>
            <div class="chapter-num">{{ book.lastChapterNum }}</div>
          </div>
          <div class="book-time">
            <div class="time-item" v-if="book.updateTime">
              <i class="el-icon-time"></i>
              <span>最后阅读：{{ formatDate(book.updateTime) }}</span>
            </div>
            <div class="time-item" v-if="book.createTime">
              <i class="el-icon-date"></i>
              <span>添加时间：{{ formatDate(book.createTime) }}</span>
            </div>
          </div>
          <div class="book-actions">
            <el-button 
              type="text" 
              class="delete-btn"
              @click="handleDelete(book)"
            >
              <i class="el-icon-delete"></i> 删除
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <el-pagination
      v-show="total > 0"
      :current-page="currentPage"
      :page-size="pageSize"
      :total="total"
      layout="prev, pager, next, jumper"
      @current-change="handleCurrentChange"
      class="pagination"
    />
  </div>
</template>

<script>
import store from "@/store";
import { getBookShelfByUserId, getNovelContent, getNovelChapter, deleteBookShelf, deleteBatchBookShelf } from "@/api/bookshelf/bookshelf";

export default {
  name: "Bookshelf",
  data() {
    return {
      userId: store.state.user.id,
      bookshelfListByUserId: [],
      selectedBooks: [],
      total: 0,
      currentPage: 1,
      pageSize: 10
    };
  },
  computed: {
    displayBooks() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = Math.min(start + this.pageSize, this.bookshelfListByUserId.length);
      console.log(`当前页: ${this.currentPage}, 每页数量: ${this.pageSize}`);
      console.log(`显示范围: ${start} 到 ${end}, 总数据量: ${this.bookshelfListByUserId.length}`);
      return this.bookshelfListByUserId.slice(start, end);
    }
  },
  created() {
    this.getBookShelfByUserId();
  },
  methods: {
    /** 根据用户id查询书架信息 */
    getBookShelfByUserId() {
      if (!this.userId) {
        this.$message.error('请先登录');
        return;
      }
      
      getBookShelfByUserId(this.userId).then(response => {
        this.bookshelfListByUserId = (response.rows || []).map(book => ({
          ...book,
          selected: false
        }));
        this.total = this.bookshelfListByUserId.length;
        console.log(`获取到 ${this.total} 本书`);
      }).catch(error => {
        console.error('获取书架信息失败:', error);
        this.$message.error('获取书架信息失败');
      });
    },
    
    /** 处理选择变化 */
    handleSelectionChange(book) {
      if (book.selected) {
        this.selectedBooks.push(book);
      } else {
        const index = this.selectedBooks.findIndex(b => b.title === book.title);
        if (index > -1) {
          this.selectedBooks.splice(index, 1);
        }
      }
    },
    
    /** 处理单个删除 */
    handleDelete(book) {
      this.$confirm('确定要从书架中移除《' + book.title + '》吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteBookShelf({
          userId: this.userId,
          title: book.title
        }).then(response => {
          if (response.code === 200) {
            this.$message.success('删除成功');
            this.getBookShelfByUserId(); // 刷新列表
          } else {
            this.$message.error(response.msg || '删除失败');
          }
        }).catch(error => {
          console.error('删除失败:', error);
          this.$message.error('删除失败');
        });
      }).catch(() => {
        // 用户取消操作
      });
    },
    
    /** 处理批量删除 */
    handleBatchDelete() {
      if (this.selectedBooks.length === 0) {
        this.$message.warning('请选择要删除的书籍');
        return;
      }
      
      const titles = this.selectedBooks.map(book => book.title);
      this.$confirm(`确定要删除选中的 ${titles.length} 本书吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteBatchBookShelf({
          userId: this.userId,
          titles: titles
        }).then(response => {
          if (response.code === 200) {
            this.$message.success('批量删除成功');
            this.selectedBooks = [];
            this.getBookShelfByUserId(); // 刷新列表
          } else {
            this.$message.error(response.msg || '批量删除失败');
          }
        }).catch(error => {
          console.error('批量删除失败:', error);
          this.$message.error('批量删除失败');
        });
      }).catch(() => {
        // 用户取消操作
      });
    },
    
    /** 格式化日期 */
    formatDate(dateString) {
      if (!dateString) return '';
      const date = new Date(dateString);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}`;
    },
    
    /** 跳转到详情页 */
    goToDetail(book) {
      Promise.all([
        getNovelContent(book.title),
        getNovelChapter(book.title)
      ]).then(([contentRes, chapterRes]) => {
        this.$router.push({
          path: '/novel/detail',
          query: {
            title: book.title,
            content: contentRes.data,
            chapters: chapterRes.data
          }
        });
      }).catch(error => {
        this.$message.error('获取小说信息失败：' + error.message);
      });
    },

    /** 处理页码变化 */
    handleCurrentChange(val) {
      console.log(`页码变化: ${this.currentPage} -> ${val}`);
      this.currentPage = val;
    }
  }
};
</script>

<style scoped>
.bookshelf-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.bookshelf-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding: 0 10px;
}

.bookshelf-title {
  font-size: 24px;
  color: #333;
  margin: 0;
}

.bookshelf-actions {
  display: flex;
  align-items: center;
  gap: 20px;
}

.book-count {
  font-size: 14px;
  color: #666;
}

.empty-bookshelf {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}

.books-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 25px;
  padding: 15px;
  min-height: 400px;
}

.book-card {
  background: #fff;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
  width: 100%;
}

.book-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
}

.book-cover {
  position: relative;
  height: 320px;
  overflow: hidden;
  background-color: #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.book-cover img {
  width: 100%;
  height: 100%;
  object-fit: contain;
  transition: transform 0.3s ease;
  background-color: #fff;
}

.book-card:hover .book-cover img {
  transform: scale(1.05);
}

.book-category {
  position: absolute;
  top: 10px;
  right: 10px;
  background: rgba(0, 0, 0, 0.6);
  color: #fff;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.book-info {
  padding: 20px;
}

.book-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.book-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin: 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  cursor: pointer;
  flex: 1;
  margin-right: 10px;
}

.book-title:hover {
  color: #409EFF;
}

.book-author {
  font-size: 16px;
  color: #666;
  margin-bottom: 12px;
}

.book-progress {
  font-size: 14px;
  color: #999;
}

.last-read {
  margin-bottom: 6px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.chapter-num {
  color: #f56c6c;
  font-weight: bold;
  font-size: 14px;
}

.book-time {
  margin-top: 12px;
  font-size: 12px;
  color: #999;
}

.time-item {
  display: flex;
  align-items: center;
  gap: 4px;
  margin-bottom: 4px;
}

.time-item i {
  font-size: 14px;
  color: #909399;
}

.time-item:last-child {
  margin-bottom: 0;
}

.read-status {
  position: absolute;
  top: 10px;
  left: 10px;
  background: rgba(0, 0, 0, 0.6);
  color: #fff;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.read-status.reading {
  background: rgba(64, 158, 255, 0.8);
}

.book-actions {
  margin-top: 12px;
  display: flex;
  justify-content: flex-end;
}

.delete-btn {
  color: #f56c6c;
}

.delete-btn:hover {
  color: #f78989;
}

.pagination {
  margin-top: 30px;
  text-align: center;
  padding: 20px 0;
}
</style>
